// pages/create-resume/create-resume.js
const initialForm = {
  templateId: null,
  studentId: wx.getStorageSync('username'),
  resumeName: '',
  name: '',
  birthDate: '',
  phone: '',
  politicalStatus: '',
  email: '',
  school: '',
  education: '本科',
  educations: [{
    school: '',
    major: '',
    courses: '',
    startDate: '',
    endDate: ''
  }],
  internships: [{
    company: '',
    position: '',
    startDate: '',
    endDate: '',
    responsibilities: ''
  }],
  campuses: [{
    activityName: '',
    role: '',
    description: '',
    startDate: '', // 新增开始时间
    endDate: ''    // 新增结束时间
  }],
  selfEvaluation: ''
}

Page({
  data: {
    templates: [],
    templateIndex: 0,
    educationList: ['本科', '硕士', '博士', '其他'],
    educationIndex: 0,
    form: JSON.parse(JSON.stringify(initialForm))
  },

  onLoad() {
    this.loadTemplates()
  },

  // 加载模板数据
  async loadTemplates() {
    try {
      wx.request({
        url: 'http://192.168.172.134:5000/api/admin/resumes/all',
        method: 'GET',
        success: (res) => {
          if (res.data.code === 200) {
            this.setData({ templates: res.data.data })
          } else {
            wx.showToast({ title: '模板加载失败', icon: 'none' })
          }
        },
      })
    } catch (error) {
      wx.showToast({ title: '模板加载失败', icon: 'none' })
    }
  },

  // 模板选择处理
  handleTemplateChange(e) {
    const index = e.detail.value
    this.setData({ 
      templateIndex: index,
      'form.templateId': this.data.templates[index].id
     })
  },

  //基本信息输入处理
  handleInput(e) {
    const { field } = e.currentTarget.dataset
    const value = e.detail.value
    this.setData({
      [`form.${field}`]: value
    })
  },

  //出生日期选择
  handleBirthdayChange(e) {
    this.setData({
      'form.birthDate': e.detail.value
    })
  },

  //学历选择器
  handleEducationChange(e) {
    const index = e.detail.value
    this.setData({
      educationIndex: index,
      'form.education': this.data.educationList[index]
    })
  },

  // 添加教育经历
  addEducation() {
    const newEducations = [...this.data.form.educations]
    newEducations.push({
      school: '',
      major: '',
      courses: '',
      startDate: '',
      endDate: ''
    })
    this.setData({
      'form.educations': newEducations
    })
  },

  // 删除教育经历
  removeEducation(e) {
    const index = e.currentTarget.dataset.index
    const newEducations = this.data.form.educations.filter((_, i) => i !== index)
    this.setData({
      'form.educations': newEducations
    })
  },

  // 教育经历输入处理
  handleEduInput(e) {
    const { index, field } = e.currentTarget.dataset
    const value = e.detail.value
    const path = `form.educations[${index}].${field}`
    this.setData({ [path]: value })
  },

  // 教育经历日期选择
  handleEduDateChange(e) {
    const { index, type } = e.currentTarget.dataset
    const value = e.detail.value
    const path = `form.educations[${index}].${type}Date`
    this.setData({ [path]: value })
  },

  // 添加实习经历
  addExperience() {
    const newExperiences = [...this.data.form.internships]
    newExperiences.push({
      company: '',
      position: '',
      startDate: '',
      endDate: '',
      responsibilities: ''
    })
    this.setData({
      'form.internships': newExperiences
    })
  },

  // 删除实习经历
  removeExperience(e) {
    const index = e.currentTarget.dataset.index
    const newExperiences = this.data.form.internships.filter((_, i) => i !== index)
    this.setData({
      'form.internships': newExperiences
    })
  },

  // 实习经历输入处理
  handleExpInput(e) {
    const { index, field } = e.currentTarget.dataset
    const value = e.detail.value
    const path = `form.internships[${index}].${field}`
    this.setData({ [path]: value })
  },

  // 实习经历日期选择
  handleExpDateChange(e) {
    const { index, type } = e.currentTarget.dataset
    const value = e.detail.value
    const path = `form.internships[${index}].${type}Date`
    this.setData({ [path]: value })
  },

  //添加校园经历
  addProject() {
    const newProjects = [...this.data.form.campuses]
    newProjects.push({
      activityName: '',
      role: '',
      description: '',
      startDate: '', // 新增开始时间
      endDate: ''    // 新增结束时间
    })
    this.setData({
      'form.campuses': newProjects
    })
  },

  // 删除校园经历
  removeProject(e) {
    const index = e.currentTarget.dataset.index
    const newProjects = this.data.form.campuses.filter((_, i) => i !== index)
    this.setData({
      'form.campuses': newProjects
    })
  },

  // 校园经历输入处理
  handleProjectInput(e) {
    const { index, field } = e.currentTarget.dataset
    const value = e.detail.value
    const path = `form.campuses[${index}].${field}`
    this.setData({ [path]: value })
  },

  // 校园经历日期选择
  handleProjectDateChange(e) {
    const { index, type } = e.currentTarget.dataset
    const value = e.detail.value
    const path = `form.campuses[${index}].${type}Date`
    this.setData({ [path]: value })
  },

  // 表单提交
  async handleSubmit(e) {
    if (!this.validateForm()) return

    try {
      await wx.request({
        url: 'http://192.168.172.134:5000/api/createResume',
        method: 'POST',
        data: this.data.form,
        success: () => {
          wx.showToast({ title: '创建成功' })
          wx.navigateBack()
        },
        fail: () => {
          wx.showToast({ title: '提交失败', icon: 'none' })
        }
      })
    } catch (error) {
      wx.showToast({ title: '网络错误', icon: 'none' })
    }
  },

  // 表单验证
  validateForm() {
    const { form } = this.data
    const requiredFields = [
      { field: 'resumeName', message: '请填写简历标题' },
      { field: 'name', message: '请填写姓名' },
      { field: 'phone', message: '请填写手机号' },
      { field: 'email', message: '请填写邮箱' },
      { field: 'school', message: '请填写毕业院校' }
    ]

    for (const { field, message } of requiredFields) {
      if (!form[field]?.trim()) {
        wx.showToast({ title: message, icon: 'none' })
        return false
      }
    }

    // 验证手机号格式
    const phoneReg = /^1[3-9]\d{9}$/
    if (!phoneReg.test(form.phone)) {
      wx.showToast({ title: '手机号格式不正确', icon: 'none' })
      return false
    }

    // 验证邮箱格式
    const emailReg = /^[a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$/
    if (!emailReg.test(form.email)) {
      wx.showToast({ title: '邮箱格式不正确', icon: 'none' })
      return false
    }

    // 验证教育经历
    for (const edu of form.educations) {
      if (!edu.school.trim() || !edu.major.trim()) {
        wx.showToast({ title: '请完善教育经历', icon: 'none' })
        return false
      }
    }

    return true
  },

  // 其他事件处理...
})